package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.comment.service.CommentRepayService;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Resource
    MongoTemplate mongoTemplate;
    @Resource
    UserFeign userFeign;

        @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
//        1. 校验参数
//        评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
//        2. 条件查询评论回复信息
//​	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate())).limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
//        3. 检查是否登录
//​	3.1 如果未登录直接 返回评论回复列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);//   TODO 直接返回回复列表
        }
//​	3.2 如果登录，需要判断哪些回复点过赞
//​	思路:
//​	     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        List<ApCommentRepayVO> apCommentRepayVOS = new ArrayList<>();
        List<String> idList = apCommentRepays.stream().map(o -> o.getId()).collect(Collectors.toList());
        Query query1 = new Query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
//​	     遍历 当前回复列表，将每一个回复信息 封装成 vo
        if (CollectionUtils.isNotEmpty(apCommentRepayLikes) && CollectionUtils.isNotEmpty(apCommentRepays)) {
            apCommentRepays.forEach(apCommentRepay -> {
                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
                //遍历当前用户的点赞列表
                apCommentRepayLikes.forEach(apCommentRepayLike -> {
                    // 文章评论列表id 和 当前用户点赞评论列表id是否相等
                    if (apCommentRepay.getId().equals(apCommentRepayLike.getCommentRepayId())) {
                        // 其中如果当前评论id在点赞记录中存在  设置operation字段为0
                        apCommentRepayVO.setOperation((short) 0);
                    }
                });
                apCommentRepayVOS.add(apCommentRepayVO);
            });
            return ResponseResult.okResult(apCommentRepayVOS);
        }
        return ResponseResult.okResult(apCommentRepays);
    }


//    @Override
//    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
//        //1. 校验参数
//        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
//        if (dto == null || dto.getCommentId() == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }
//        if (dto.getSize() == null || dto.getSize() == 0) {
//            dto.setSize(10);
//        }
//        if (dto.getMinDate() == null) {
//            dto.setMinDate(new Date());
//        }
//        //2. 条件查询评论回复信息
//        //​	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
//        ApUser user = AppThreadLocalUtils.getUser();
//        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
//                .and("createdTime").lt(dto.getMinDate()))
//                .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(dto.getSize());
//        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
//        //3. 检查是否登录
//        if (user == null) {
//            //​	3.1 如果未登录直接 返回评论回复列表
//            return ResponseResult.okResult(apCommentRepayList);
//        }
//        //​	3.2 如果登录，需要判断哪些回复点过赞
//        //​	思路:
//        //​	     基于当前列表 回复id集合
//        List<String> idList = apCommentRepayList.stream().map(o -> o.getId()).collect(Collectors.toList());
//        //​	     遍历 当前回复列表，将每一个回复信息 封装成 vo
//        List<ApCommentRepayVO> apCommentRepayVOList = new ArrayList<>();
//        //登录人id 查询回复点赞列表
//        Query query1 = Query.query(Criteria.where("commentRepayId").
//                in(idList).and("authorId").is(user.getId()));
//        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
//        List<String> likedCommentRepayIds = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());
////        if (apCommentRepayLikes!=null) {
//            apCommentRepayList.forEach(apCommentRepay -> {
//                //注意要new一个对象出来，不然不好插入
//                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
//                BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
//    //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
//                apCommentRepayLikes.forEach(apCommentRepayLike -> {
//                    if (apCommentRepayLike.getCommentRepayId().equals(apCommentRepay.getId())) {
//                        apCommentRepayVO.setOperation((short) 0);
//                    }
//                });
//                apCommentRepayVOList.add(apCommentRepayVO);
//            }
//            );
//            return ResponseResult.okResult(apCommentRepayVOList);
////        }
////        return ResponseResult.okResult(apCommentRepayList);
//    }



    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1.检查参数
        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.安全过滤,自行实现
        //4.保存评论
        ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
        if (userResult.getCode() != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, userResult.getErrorMessage());
        }
        user = userResult.getData();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //****更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //​       回复id不能为空   operation 必须 0 或 1
        //​       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //​       校验回复信息是否存在
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2. 如果是点赞  判断是否点过赞
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        Short operation = dto.getOperation();
        //​      点过赞提示请勿重复点赞
        if (apCommentRepayLike != null && operation.intValue() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "你已经点过赞");
        }
        //​      未点过赞， 保存点赞信息
        if (operation.intValue() == 0) {
            //​并将回复信息的点赞数量字段+1
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation(operation);
            mongoTemplate.save(apCommentRepayLike);
        } else {
            //3. 如果是取消赞
            commentRepay.setLikes(commentRepay.getLikes() < 0 ? 0 : commentRepay.getLikes() - 1);
            mongoTemplate.save(commentRepay);
            //​      删除点赞信息
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        //4. 返回当前回复的最新点赞数量      数据的key:  likes
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
